package cn.yhp.mybatis.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * 通过类加载器获取某资源输入流
 * @author yhp
 * @date 2023/11/18
 */
public class Resources {

    public static Reader getResourceAsReader(String resource) throws IOException {
        return new InputStreamReader(getResourceAsStream(resource));
    }

    private static InputStream getResourceAsStream(String resource) throws IOException {
        ClassLoader[] classLoaders = getClassLoaders();
        for (ClassLoader classLoader : classLoaders) {
            // 核心：类加载器获取资源路径的输入流
            InputStream inputStream = classLoader.getResourceAsStream(resource);
            if (null!=inputStream){
                return inputStream;
            }
        }
        throw new IOException("找不到资源："+resource);
    }

    /**
     * 获取类加载器，系统，线程上下文加载器
     * @return
     */
    private static ClassLoader[] getClassLoaders() {
        return new ClassLoader[]{ClassLoader.getSystemClassLoader(),
                Thread.currentThread().getContextClassLoader()};
    }

    /**
     * 创建class对象
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    public static Class<?> classForName(String className) throws ClassNotFoundException {
        return Class.forName(className);
    }
}
